package com.example.shortvideobackend.service;

import com.example.shortvideobackend.entity.LiveStream;
import com.example.shortvideobackend.entity.User;
import com.example.shortvideobackend.repository.LiveStreamRepository;
import com.example.shortvideobackend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class LiveStreamService {

    @Autowired
    private LiveStreamRepository liveStreamRepository;

    @Autowired
    private UserRepository userRepository;

    // 创建直播流
    public LiveStream createLiveStream(String title, String description, Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        LiveStream liveStream = new LiveStream();
        liveStream.setTitle(title);
        liveStream.setDescription(description);
        liveStream.setUser(user);
        liveStream.setStreamKey(generateStreamKey());
        liveStream.setStreamUrl("/live/" + liveStream.getStreamKey());
        liveStream.setStatus(LiveStream.LiveStatus.OFFLINE);
        liveStream.setViewers(0);
        liveStream.setLikes(0);

        return liveStreamRepository.save(liveStream);
    }

    // 开始直播
    public LiveStream startLiveStream(Long streamId, Long userId) {
        LiveStream liveStream = liveStreamRepository.findById(streamId)
                .orElseThrow(() -> new RuntimeException("直播流不存在"));

        if (!liveStream.getUser().getId().equals(userId)) {
            throw new RuntimeException("无权操作此直播流");
        }

        liveStream.setStatus(LiveStream.LiveStatus.LIVE);
        liveStream.setStartedAt(LocalDateTime.now());
        liveStream.setEndedAt(null);

        return liveStreamRepository.save(liveStream);
    }

    // 结束直播
    public LiveStream endLiveStream(Long streamId, Long userId) {
        LiveStream liveStream = liveStreamRepository.findById(streamId)
                .orElseThrow(() -> new RuntimeException("直播流不存在"));

        if (!liveStream.getUser().getId().equals(userId)) {
            throw new RuntimeException("无权操作此直播流");
        }

        liveStream.setStatus(LiveStream.LiveStatus.ENDED);
        liveStream.setEndedAt(LocalDateTime.now());

        return liveStreamRepository.save(liveStream);
    }

    // 获取所有直播中的流
    public List<LiveStream> getLiveStreams() {
        return liveStreamRepository.findByStatusOrderByStartedAtDesc(LiveStream.LiveStatus.LIVE);
    }

    // 根据ID获取直播流
    public LiveStream getLiveStreamById(Long id) {
        return liveStreamRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("直播流不存在"));
    }

    // 根据streamKey获取直播流
    public LiveStream getLiveStreamByKey(String streamKey) {
        return liveStreamRepository.findByStreamKey(streamKey)
                .orElseThrow(() -> new RuntimeException("直播流不存在"));
    }

    // 获取用户的直播流
    public List<LiveStream> getUserLiveStreams(Long userId) {
        return liveStreamRepository.findByUser_Id(userId);
    }

    // 增加观看人数
    public void incrementViewers(Long streamId) {
        Optional<LiveStream> liveStreamOpt = liveStreamRepository.findById(streamId);
        if (liveStreamOpt.isPresent()) {
            LiveStream liveStream = liveStreamOpt.get();
            liveStream.setViewers(liveStream.getViewers() + 1);
            liveStreamRepository.save(liveStream);
        }
    }

    // 增加点赞数
    public void incrementLikes(Long streamId) {
        Optional<LiveStream> liveStreamOpt = liveStreamRepository.findById(streamId);
        if (liveStreamOpt.isPresent()) {
            LiveStream liveStream = liveStreamOpt.get();
            liveStream.setLikes(liveStream.getLikes() + 1);
            liveStreamRepository.save(liveStream);
        }
    }

    // 删除直播流
    public void deleteLiveStream(Long streamId, Long userId) {
        LiveStream liveStream = liveStreamRepository.findById(streamId)
                .orElseThrow(() -> new RuntimeException("直播流不存在"));

        if (!liveStream.getUser().getId().equals(userId)) {
            throw new RuntimeException("无权删除此直播流");
        }

        liveStreamRepository.delete(liveStream);
    }

    // 生成唯一的streamKey
    private String generateStreamKey() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
} 